<template>
  <div ref="topPanel" :class="{show: show}" class="topPanel-container testtttt">
    <div class="topPanel-background" @click="show = false" />
    <div class="topPanel">
      <div class="handle-button" :style="{'left': buttonLeft + 'px', 'background-color': theme}" @click="togglePanel">
        <i :class="show ? 'el-icon-close' : 'el-icon-setting'" />
      </div>
      <div class="topPanel-items h-full">
        <slot />
      </div>
    </div>
  </div>
</template>

<script>
import { addClass, removeClass } from '@/utils'

export default {
  name: 'TopPanel',
  props: {
    clickNotClose: {
      default: false,
      type: Boolean
    },
    buttonLeft: {
      default: window.innerWidth / 2 - 24 - 100, // Center the button
      type: Number
    }
  },
  data() {
    return {
      show: false
    }
  },
  computed: {
    theme() {
      return this.$store.state.settings.theme
    }
  },
  watch: {
    show(value) {
      if (value && !this.clickNotClose) {
        this.addEventClick()
      }
      if (value) {
        addClass(document.body, 'showTopPanel')
      } else {
        removeClass(document.body, 'showTopPanel')
      }
    }
  },
  mounted() {
    this.insertToBody()
  },
  beforeDestroy() {
    const elx = this.$refs.topPanel
    if (elx) elx.remove()
  },
  methods: {
    togglePanel() {
      this.show = !this.show
    },
    addEventClick() {
      window.addEventListener('click', this.closePanelOutsideClick)
    },
    closePanelOutsideClick(evt) {
      if (!evt.target.closest('.topPanel')) {
        this.show = false
        window.removeEventListener('click', this.closePanelOutsideClick)
      }
    },
    insertToBody() {
      const elx = this.$refs.topPanel
      const body = document.querySelector('body')
      body.insertBefore(elx, body.firstChild)
    }
  }
}
</script>
<style lang="scss" scoped>
.topPanel-background {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: rgba(0, 0, 0, 0.5);
  z-index: 100;
  transition: opacity 0.3s cubic-bezier(0.7, 0.3, 0.1, 1), pointer-events 0.3s cubic-bezier(0.7, 0.3, 0.1, 1);
  opacity: 0;
  pointer-events: none;
}

.topPanel {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  min-height: 260px;
  transform: translateY(-100%);
  background: #fff;
  z-index: 101;
  transition: transform 0.25s cubic-bezier(0.7, 0.3, 0.1, 1);
}

.show {
  .topPanel-background {
    opacity: 1;
    pointer-events: auto;
  }
  .topPanel {
    transform: translateY(0);
  }
}

.handle-button {
  position: absolute;
  bottom: -48px;
  left: calc(50% - 24px);
  width: 48px;
  height: 48px;
  text-align: center;
  font-size: 24px;
  color: #fff;
  line-height: 48px;
  cursor: pointer;
  border-radius: 0 0 6px 6px;
  z-index: 102;
}
.topPanel-items {
  padding-left: 210px;
}
</style>
